#!/bin/bash

# ---------------------------------------------------------------------	#
# buildvdimage	- Build raw disk image for VirtualBox and install 	#
#		  debian system on it. So we can start using the new	#
#		  virtual machine immediately without to install and	#
#		  configure that system manually.			#
#									#
#		  Part of this script was modified from 		#
#		  http://blog.quinthar.com/2008/07/			#
#			building-1gb-bootable-qemu-image-using.html	#
#									#
# version 0.1	- cj (2010-06-25) init.					#
# version 0.2   - cj (2010-07-09) ...					#
# version 0.2e  - cj (2010-07-12) various fixed.			#
# version 0.3	- cj (2010-07-17) various fixed, use with blade{3,4}	#
# version 0.3a	- cj (2010-07-20) add tasksel, and additional pacakages	#
# version 0.4	- cj (2010-07-26) WUNCA22 version.			#
# version 0.5	- cj (2010-08-03) ...					#
# version 0.6	- cj (2010-08-27) ...					#
# ---------------------------------------------------------------------	#

export LANG=C

VBOXHDD="/home/cj/.VirtualBox/HardDisks"
DIST="lenny"

SVR="ftp.th.debian.org"

# FTPSITE="$SVR"

FTPSITE="localhost:3142/$SVR"
VMFTPSITE="10.0.2.2:3142/$SVR"

# DEBREPO="http://$SVR/debian"
# DEBREPO="file:///var/cache/apt-cacher-ng/$SVR/debian"

DEBREPO="http://$FTPSITE/debian"

# TASKLIST="thai-desktop"
TASKLIST=""
PKGLIST="netcat zenity tshark wireshark"

USER="cj"
PASSWORD="coecj"
USERNAME="Chatchai J"

VMHOSTNAME="test"

SWAPSIZE=128
BOOTSIZE=128
HOMESIZE=256

MOUNT="mount"

dumphdinfo="VBoxManage -q internalcommands dumphdinfo"

hdinfo="/tmp/${VMHOSTNAME}.hdinfo"
fstab="/tmp/${VMHOSTNAME}.fstab"
devlist="/tmp/${VMHOSTNAME}.devlist"
parted="/tmp/${VMHOSTNAME}.parted"

# ---------------------------------------------------------------------	#
# Check that whether binary needed for this setup  is existed.		#
# ---------------------------------------------------------------------	#

check_command() {
	local CMD="$1"
	if [ ! -x "$CMD" ]; then
		echo "$CMD not exist."
		exit
	fi
}

# ---------------------------------------------------------------------	#
# Create various configuration files					#
# ---------------------------------------------------------------------	#

### ----- /etc/resolv.conf ----- ###
# It's difficult to generate /etc/resolv.conf by ourself,
# but it should be safe to copy from building host to the VM
# since it is likely to be used in the same environment.

create_resolv_conf() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: resolv.conf" && exit
	sudo cp /etc/resolv.conf $MOUNT/etc
}

### ----- /etc/hosts ----- ###
# Standard /etc/hosts, without self IP address and name...
create_hosts() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: hosts" && exit
	cat << _EOT_ > /tmp/hosts.$$
127.0.0.1	localhost localhost.localdomain

::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
_EOT_
	sudo mv -vf /tmp/hosts.$$ $MOUNT/etc/hosts
}

### ----- /etc/hostname ----- ###
create_hostname() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: hostname" && exit
	sudo sh -c "(echo '$VMHOSTNAME' > $MOUNT/etc/hostname)"
}

### ----- /etc/fstab ----- ###
create_fstab() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: fstab" && exit
	cat << _EOT_ > /tmp/fstab.$$
# <file system> <mount point> <types> <options> <dump> <pass>
proc		/proc	proc	defaults		0	0
_EOT_
	cat $fstab >> /tmp/fstab.$$
	sudo mv -vf /tmp/fstab.$$ $MOUNT/etc/fstab
}

### ----- /etc/kernel-img.conf ----- ###
create_kernel_img_conf() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: kernel-img.conf" && exit
	cat << _EOT_ > /tmp/kernel-img.conf.$$
do_symlinks = yes
relative_links = yes
do_bootloader = yes
do_bootfloppy = no
do_initrd = yes
link_in_boot = no
_EOT_
	sudo mv -vf /tmp/kernel-img.conf.$$ $MOUNT/etc/kernel-img.conf
}

### ----- /etc/apt/sources.list ----- ### packages update during install ###
create_tmp_apt_sources_list() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: sources.list" && exit
	cat << _EOT_ > /tmp/sources.list.$$
deb http://${FTPSITE}/debian lenny main
_EOT_
	sudo mv -vf /tmp/sources.list.$$ $MOUNT/etc/apt/sources.list
}

### ----- /etc/apt/sources.list ----- ### supposed to be real one ###
create_real_apt_sources_list() {
	local MOUNT="$1"
	
	[ -z "$MOUNT" ] && echo "ERR: sources.list" && exit
	cat << _EOT_ > /tmp/sources.list.$$
deb http://${FTPSITE}/debian lenny main contrib non-free
deb http://${FTPSITE}/debian-security lenny/updates main contrib non-free
_EOT_
	sudo mv -vf /tmp/sources.list.$$ $MOUNT/etc/apt/sources.list
}

### ----- /etc/apt/sources.list ----- ### real one using under VM ###
create_vm_apt_sources_list() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: sources.list" && exit
	cat << _EOT_ > /tmp/final-sources.list.$$
deb http://${VMFTPSITE}/debian lenny main contrib non-free
deb http://${VMFTPSITE}/debian-security lenny/updates main contrib non-free
_EOT_
	sudo mv -vf /tmp/final-sources.list.$$ $MOUNT/etc/apt/sources.list
}

### ----- /etc/network/interfaces ----- ###
create_network_interfaces() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: interfaces" && exit
	cat << _EOT_ > /tmp/interfaces.$$
auto lo
iface lo inet loopback

allow-hotplug eth0
iface eth0 inet dhcp
_EOT_

	sudo mv -f /tmp/interfaces.$$ $MOUNT/etc/network/interfaces
}

### ----- various config files in /etc ----- ###
create_config_files() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: config files" && exit
	create_resolv_conf $MOUNT		# /etc/resolv.conf
	create_hosts $MOUNT			# /etc/hosts
	create_hostname $MOUNT			# /etc/hostname
	create_fstab $MOUNT			# /etc/fstab
	create_kernel_img_conf $MOUNT		# /etc/kernel_img_conf
	create_tmp_apt_sources_list $MOUNT	# /etc/apt/sources.list
	create_network_interfaces $MOUNT	# /etc/network/interfaces
}

### ----- /boot/grub/menu.lst ----- ###
create_boot_grub_menu_list() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: menu.list" && exit
	# check whether if /boot are in different partition
	local boot="$(grep /boot $fstab)"

	# No separate boot partition?
	if [ -z "$boot" ]; then
		BOOT="/boot"
		ROOT="/dev/sda1"
	else
		BOOT=""
		ROOT="/dev/sda2"
	fi

	cat << _EOT_ > /tmp/menu.lst.$$
timeout 3
default 0

_EOT_

	(
	cd $MOUNT/boot;
	for k in vmlinuz-*; do
		v=$(echo $k | cut -f2- -d-)
		if [ -f "initrd.img-$v" ]; then
			cat << _EOT_ >> /tmp/menu.lst.$$
title Debian Linux $v
root (hd0,0)
kernel $BOOT/vmlinuz-$v root=$ROOT ro verbose 
initrd $BOOT/initrd.img-$v

_EOT_
		fi
	done
	)

	sudo mv -f /tmp/menu.lst.$$ $MOUNT/boot/grub/menu.lst
}

# ---------------------------------------------------------------------	#
# create_policy_rc_d	Create policy-rc.d for handle tasksel tasks	#
#			install on chroot environment.			#
# ---------------------------------------------------------------------	#

create_policy_rc_d() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: policy-rc.d" && exit
	cat << _EOT_ > /tmp/policy-rc.d.$$
#!/bin/sh
exit 101
_EOT_
	chmod a+rx /tmp/policy-rc.d.$$
	sudo mv -vf /tmp/policy-rc.d.$$ $MOUNT/usr/sbin/policy-rc.d
}

# ---------------------------------------------------------------------	#
# config_grub	This must be done after grub and kernel has been	#
#		installed to the raw disk device.			#
# ---------------------------------------------------------------------	#

config_grub() {
	local device="$1" MOUNT="$2"

	[ -z "$device" ] && echo "ERR: device of grub" && exit
	[ -z "$MOUNT" ] && echo "ERR: grub.input" && exit
	cat << _EOT_ > /tmp/grub.input
device (hd0) $device
root (hd0,0)
setup --stage2=/boot/grub/stage2 (hd0)
quit
_EOT_

	sudo mkdir $MOUNT/boot/grub
	sudo cp $MOUNT/usr/lib/grub/i386-pc/* $MOUNT/boot/grub

	create_boot_grub_menu_list $MOUNT

	sudo chroot $MOUNT grub --batch --device-map=/dev/null	\
		< /tmp/grub.input 				\
		> /tmp/grub.log

	# If first time failed, then try once again, ...
	if [ "$(grep ^Error /tmp/grub.log)" ]; then
		sudo chroot $MOUNT grub --batch --device-map=/dev/null	\
			< /tmp/grub.input 				\
			> /tmp/grub2.log

		# If it still failed, then we gave up!
		if [ "$(grep ^Error /tmp/grub2.log)" ]; then
			echo "Failed to install grub."
			echo "Please see /tmp/grub.log /tmp/grub2.log"
			exit
		fi
	fi
}

# ---------------------------------------------------------------------	#
# binding_mount		Binding mount points to chroot environment	#
# ---------------------------------------------------------------------	#

binding_mount() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: mount" && exit
	# Binding mount point
	echo "Bind /proc to $MOUNT/proc"
	sudo mount --bind /proc $MOUNT/proc

	echo "Mount $MOUNT/dev/pts"
	sudo mount -t devpts none $MOUNT/dev/pts
}

# ---------------------------------------------------------------------	#
# binding_umount	Un-binding mount points from chroot environment	#
# ---------------------------------------------------------------------	#

binding_umount() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: umount" && exit
	sudo umount $MOUNT/proc
	sudo umount $MOUNT/dev/pts
}

# ---------------------------------------------------------------------	#
# create_vdi	- Create the fixed size VDI disk image file.		#
# ---------------------------------------------------------------------	#

create_vdi() {
	local name="$1" size="$2"

	[ -f "$name" ] && echo "File '$name' already exist." && exit
	[ -z "$size" ] && echo "ERR: create_vdi size" && exit

	VBoxManage -q createhd --filename "$name" --size "$size" \
		--format VDI --variant Fixed
}

# ---------------------------------------------------------------------	#
# verify_vdi	- Verify that the vdi is actual fixed size VDI image.	#
# ---------------------------------------------------------------------	#

verify_vdi() {
	local file="$1"

	[ -z "$file" ] && echo "ERR: verify_vdi filename" && exit

	$dumphdinfo $file > $hdinfo
	if [ "$(grep 'Format autodetect failed' $hdinfo)" ]; then
		echo "File '$file' is not a VDI file."
		exit
	fi

	version=$(	grep '^Header: Version=' $hdinfo	|\
			cut -f3 -d=				|\
			cut -f1 -d' '				)

	[ -z "$version" -o "$version" != "2" ]				&& \
		echo "File '$file' is not a fixed disk VDI image."	&& \
		exit

}

# ---------------------------------------------------------------------	#
# loop_dev_setup	- Setup loop device for the disk image for	#
#			  create partition on the image file.		#
# ---------------------------------------------------------------------	#

loop_dev_setup() {
	local file="$1"

	[ -z "$file" ] && echo "ERR: loop_dev_setup filename" && exit

	loopdev=$(sudo losetup -f)

	offset=$(	$dumphdinfo $file 		|\
			grep offStartData		|\
			cut -f4 -d=			)

	echo "Setup loop device $loopdev for $file"
	sudo losetup --offset $offset $loopdev $file
	sudo losetup -a

	# We need to do this first to get disksize
	sudo parted -s $loopdev mklabel msdos

	disk_size=$(sudo parted -s $loopdev print | grep ^Disk | cut -f3 -d' ')

	# Check that size should be in MB unit
	if [ "$(echo $disk_size | sed -e 's/^[0-9]*//')" != "MB" ]; then
		echo "Disk size '$disk_size' is not in MB unit."
		exit
	fi

	# Get only number part
	disk_size=$(echo $disk_size | sed -e 's/MB$//')
}

# ---------------------------------------------------------------------	#
# set_part_scheme	- Set partition scheme. Select the predefine	#
#			  partitions, for create that on disk image.	#
# ---------------------------------------------------------------------	#

set_part_scheme() {
	local scheme="$1"

	case "$scheme" in
# ---------------------------------------------------------------------	#
# /dev/sda1	/	ext3	defaults 0 1	-- everything		#
# ---------------------------------------------------------------------	#
	1)
	boot_size=0
	swap_size=0
	root_size=$disk_size
	home_size=0
	;;
# ---------------------------------------------------------------------	#
# /dev/sda1	/	ext3	defaults 0 1	-- the rest		#
# /dev/sda5	none	swap	sw	 0 0	-- 128 MB SWAP		#
# ---------------------------------------------------------------------	#
	2)
	boot_size=0
	swap_size=$SWAPSIZE
	root_size=$(( $disk_size - $swap_size ))
	home_size=0
	;;
# ---------------------------------------------------------------------	#
# /dev/sda1	/boot	ext3	defaults 0 1	-- 128 MB /boot		#
# /dev/sda2	/	ext3	defaults 0 1	-- the rest		#
# /dev/sda5	none	swap	sw	 0 0	-- 128 MB SWAP		#
# ---------------------------------------------------------------------	#
	3)
	boot_size=$BOOTSIZE
	swap_size=$SWAPSIZE
	root_size=$(( $disk_size - $boot_size - $swap_size ))
	home_size=0
	;;
# ---------------------------------------------------------------------	#
# /dev/sda1	/boot	ext3	defaults 0 1	-- 128 MB /boot		#
# /dev/sda2	/	ext3	defaults 0 1	-- the rest		#
# /dev/sda3	/home	ext3	defaults 0 1	-- 256 MB /home		#
# /dev/sda5	none	swap	sw	 0 0	-- 128 MB SWAP		#
# ---------------------------------------------------------------------	#
	4)
	home_size=$HOMESIZE
	boot_size=$BOOTSIZE
	swap_size=$SWAPSIZE
	root_size=$(( $disk_size - $boot_size - $swap_size - $home_size))
	;;

	*)	echo "Invalid scheme"
		exit
	;;
	esac

}

# ---------------------------------------------------------------------	#
# Create parition here.							#
# ---------------------------------------------------------------------	#

create_partitions() {

	[ -z "$loopdev" ] && echo "ERR: create_partitions loopdev" && exit

	boot_start=0
	boot_end=$(($boot_start + $boot_size))
	root_start=$boot_end
	root_end=$(($root_start + $root_size))
	home_start=$root_end
	home_end=$(($home_start + $home_size))
	swap_start=$home_end
	swap_end=$(($swap_start + $swap_size))
	ext_start=$swap_start
	ext_end=$swap_end

	sudo parted -s $loopdev mklabel msdos

	# clear temporary fstab file
	> $fstab
	devno=1

if [ "$boot_size" != 0 ]; then
	sudo parted -s $loopdev mkpart primary ext2 $boot_start $boot_end
	echo "/dev/sda$devno /boot ext3 errors=remount-ro 0 0" >> $fstab
	devno=$(($devno + 1))
fi
if [ "$root_size" != 0 ]; then
	sudo parted -s $loopdev mkpart primary ext2 $root_start $root_end
	echo "/dev/sda$devno / ext3 errors=remount-ro 0 0" >> $fstab
	devno=$(($devno + 1))
fi
if [ "$home_size" != 0 ]; then
	sudo parted -s $loopdev mkpart primary ext2 $home_start $home_end
	echo "/dev/sda$devno /home ext3 errors=remount-ro 0 0" >> $fstab
	devno=$(($devno + 1))
fi
if [ "$swap_size" != 0 ]; then
	devno=5
	sudo parted -s $loopdev mkpart extended $ext_start $ext_end
	sudo parted -s $loopdev mkpart logical linux-swap $swap_start $swap_end
	echo "/dev/sda$devno none swap sw 0 0" >> $fstab
	
fi
	sudo parted -s $loopdev set 1 boot on
	sudo parted -s $loopdev print > $parted
}

# ---------------------------------------------------------------------	#
# loop_part_mkfs- Make filesystem on each partition accessible by	#
#		  loop device.						#
#		  This might be the most dangerous part of this script.	#
#		  It will format filesystem without asking any question	#
# ---------------------------------------------------------------------	#

loop_part_mkfs() {
	[ -z "$devlist" -o -z "$loopdev" ] && echo "ERR: loop_part_mkfs" && exit
	# Clean up device list
	> $devlist
	sudo sfdisk -uS -l $loopdev			|\
		sed -e 's/\*//'				|\
		grep ^/					|\
		grep Linux				|\
	while read line; do
		start=$(echo $line | awk '{ print $2; }')
		end=$(echo $line | awk '{ print $3; }')
		swap=$(echo $line | grep 'swap')

		offset=$(( $start * 512 ))
		sizelimit=$(( ($end - $start) * 512 ))

		looppart=$(sudo losetup -f)
		sudo losetup --offset $offset --sizelimit $sizelimit \
			$looppart $loopdev

		# Check whether it is a "Linux swap" partition
		if [ -z "$swap" ]; then
			echo "Make e2fs on $looppart ..."
			sudo mke2fs -j $looppart
			echo "$looppart" >> $devlist
		else
			echo "Make swap on $looppart ..."
			sudo mkswap $looppart
			echo "#$looppart" >> $devlist
		fi
	done
}

# ---------------------------------------------------------------------	#
# mount_dev	Mount one device					#
# ---------------------------------------------------------------------	#

mount_dev() {
	local dev="$1" mount="$2"

	[ -z "$dev" ] && echo "device is not defined" && exit
	[ -z "$mount" ] && echo "mount point is not defined" && exit

	echo "Try mount '$dev' to '$mount'"
	sudo mount -t ext3 $dev $mount || {
		echo "Failed to mount '$dev' to '$mount'"
		exit
	}
}

# ---------------------------------------------------------------------	#
# loop_part_mount	Mount partition from loop device.		#
# ---------------------------------------------------------------------	#

# Mount loop device partition for installation
loop_part_mount() {
	local MOUNT="$1"

	[ -z "$MOUNT" ] && echo "ERR: loop_part_mount" && exit

	local LOOPDEVLIST="$(cat $devlist | grep -v ^# | tr '\n' ' ')"

	count=$(echo "$LOOPDEVLIST" | wc -w)
	p1=$(echo "$LOOPDEVLIST" | awk '{ print $1; }')
	p2=$(echo "$LOOPDEVLIST" | awk '{ print $2; }')
	p3=$(echo "$LOOPDEVLIST" | awk '{ print $3; }')
	case $count in
	1)
		mount_dev $p1 $MOUNT
	;;
	2)
		mount_dev $p2 $MOUNT
		sudo mkdir -p $MOUNT/boot 
		mount_dev $p1 $MOUNT/boot
	;;
	3)
		mount_dev $p2 $MOUNT
		sudo mkdir -p $MOUNT/boot $MOUNT/home
		mount_dev $p1 $MOUNT/boot
		mount_dev $p3 $MOUNT/home
	;;
	*)
		echo "Hmmm, looppartmount found "$count" partition list"
		echo "List = $LOOPDEVLIST"
		echo "This is unexpected, bail out"
		exit
	;;
	esac
}

# ---------------------------------------------------------------------	#
# install_tasks		Install predefined packages using tasksel	#
# ---------------------------------------------------------------------	#

install_tasks() {
	local MOUNT="$1"
	local TASKLIST=""

	[ -z "$MOUNT" ] && echo "ERR: install_tasks" && exit
	shift
	TASKLIST="$@"
	cat << _EOT_ >> /tmp/tasksel.$$
#!/bin/sh
DEBIAN_FRONTEND=noninteractive
DEBIAN_PRIORITY=critical
LANG=C
export DEBIAN_FRONTEND DEBIAN_PRIORITY LANG

_EOT_

	for task in $TASKLIST; do
		echo "tasksel --new-install install $task" >> /tmp/tasksel.$$
	done

	chmod a+rx /tmp/tasksel.$$
	sudo cp /tmp/tasksel.$$ $MOUNT/tmp/tasksel
	sudo chroot $MOUNT /tmp/tasksel
}

# ---------------------------------------------------------------------	#
# install_packages	Install additional packages			#
# ---------------------------------------------------------------------	#

install_packages() {
	local MOUNT="$1"
	local PKGLIST=""

	[ -z "$MOUNT" ] && echo "ERR: install_pacakges" && exit
	shift
	PKGLIST="$@"
	echo "Install additional package :: $PKGLIST"
	sudo chroot $MOUNT apt-get -y install $PKGLIST
}


# ---------------------------------------------------------------------	#
# cleanup_loopdev	Cleanup loop device				#
# ---------------------------------------------------------------------	#

cleanup_loopdev() {
	local LOOPDEVLIST="$(cat $devlist | tr '#' ' ' | tr '\n' ' ')"

	[ -z "$loopdev" ] && echo "ERR: cleanup_loopdev." && exit
	# then umount every loop device
	for looppart in $LOOPDEVLIST; do
		if [ "$(mount | grep ^$looppart)" ]; then
			echo "Unmount $looppart ..."
			sudo umount $looppart
		fi
	done

	# try again, cause we didn't have looppart arrange in order...
	for looppart in $LOOPDEVLIST; do
		if [ "$(mount | grep ^$looppart)" ]; then
			echo "Unmount $looppart ..."
			sudo umount $looppart
		fi
	done

	for looppart in $LOOPDEVLIST; do
		echo "Remove loop device $looppart ..."
		sudo losetup -d $looppart
	done

	sleep 3
	echo "Finally remove loop device $loopdev"
	sudo losetup -d $loopdev

	C=0
	while [ "$(sudo losetup -a | grep $loopdev)" ]; do
		sleep 3
		echo "Remove $loopdev failed, try once again"
		sudo losetup -d $loopdev
		C=$(($C + 1))
		if [ "$C" -gt 3 ]; then
			echo "Too many attempts had been made, I gave up."
			exit
		fi
	done
}

# ---------------------------------------------------------------------	#
# Main Start Here							#
# ---------------------------------------------------------------------	#

[ -z "$3" ] && echo "Usage: $0 file size scheme" && exit

file="$1"
size="$2"
scheme="$3"

if [ -z "$(echo $file | grep '\.vdi$')" ]; then
	echo "Filename should be in form 'file.vdi'"
	exit
fi

check_command /sbin/parted
check_command /usr/sbin/debootstrap
check_command /usr/bin/VBoxManage
check_command /bin/mount
check_command /sbin/losetup

[ "$size" -lt 256 -o "$size" -gt 8192 ] && {
	echo "Please choose size between 256-8192"
	exit
}

case "$scheme" in
	1|2|3|4)
	;;
	*)
		echo "Invalid scheme, please choose [1-4]"
		exit
	;;
esac

vdifile="$VBOXHDD/$file"

# Get rid of the existing one...
[ -f $vdifile ] && rm -f $vdifile

# OK now create a new one, also do create partition on it.
# We will use simple, single partition here, for simplicity.

echo "### ====================================================="
echo "### Creating VDI file and also setup it as loop device"
echo "### ====================================================="

create_vdi $file $size
verify_vdi $vdifile
loop_dev_setup $vdifile

echo "### ====================================================="
echo "### Select parition scheme"
echo "### ====================================================="

set_part_scheme $scheme

echo "### ====================================================="
echo "### Create Partitions"
echo "### ====================================================="

create_partitions

# Create filesystem on loopdevice
echo "### ====================================================="
echo "### Create filesystem on loop devices"
echo "### ====================================================="

loop_part_mkfs

echo "### ====================================================="
echo "### Create mount point '$MOUNT'"
echo "### ====================================================="

mkdir -p $MOUNT

echo "### ====================================================="
echo "### Mount filesystem to mount points"
echo "### ====================================================="

loop_part_mount $MOUNT

# Using debootstrap to install debian to raw disk image

DEBIAN_FRONTEND=noninteractive
DEBIAN_PRIORITY=critical
export DEBIAN_FRONTEND DEBIAN_PRIORITY

echo "### ====================================================="
echo "### Installing $DIST into $MOUNT"
echo "### ====================================================="

sudo debootstrap --arch i386 $DIST $MOUNT $DEBREPO

# Create various configuration files in mount point
echo "### ====================================================="
echo "### Create various config files"
echo "### ====================================================="

create_config_files $MOUNT

echo "### ====================================================="
echo "### Binding /proc and /dev/pts"
echo "### ====================================================="

binding_mount $MOUNT

# trap exit_cleanup EXIT INT

create_policy_rc_d $MOUNT

echo "### ====================================================="
echo "### Installing kernel into $MOUNT"
echo "### ====================================================="

sudo chroot $MOUNT apt-get update
sudo chroot $MOUNT apt-get -y install sudo gnupg grub linux-image-2.6-686

echo "### ====================================================="
echo "### Config grub on device $loopdev via mount point $MOUNT"
echo "### ====================================================="

config_grub $loopdev $MOUNT

echo "### ====================================================="
echo "### Install sshd"
echo "### ====================================================="

sudo chroot $MOUNT apt-get -y install ssh
sudo chroot $MOUNT /etc/init.d/ssh stop

echo "### ====================================================="
echo "### Setup user account and predefined password"
echo "### ====================================================="
sudo chroot $MOUNT usermod -p '!' root

sudo chroot $MOUNT useradd -m -c "$USERNAME" -G sudo $USER
echo "$USER:$PASSWORD" | sudo chroot $MOUNT chpasswd  -c MD5 $USER

echo "### ====================================================="
echo "### Setup sudoers"
echo "### ====================================================="

sudo sh -c "(sed -ie 's/# %sudo/%sudo/' $MOUNT/etc/sudoers)"

echo "### ====================================================="
echo "### Install root's sshd key"
echo "### ====================================================="

sudo mkdir -p $MOUNT/root/.ssh
if [ -f ~/.ssh/id_rsa.pub ]; then
	sudo cp ~/.ssh/id_rsa.pub $MOUNT/root/.ssh/authorized_keys
fi
sudo chmod -R 755 $MOUNT/root/.ssh

if [ "$TASKLIST" ]; then
	echo "### ====================================================="
	echo "### Install preselected tasks"
	echo "### ====================================================="

	install_tasks $MOUNT $TASKLIST
fi

if [ "$PKGLIST" ]; then
	echo "### ====================================================="
	echo "### Install additional packages."
	echo "### ====================================================="

	install_packages $MOUNT $PKGLIST
fi

echo "### ====================================================="
echo "### Setup vm's /etc/apt/sources.list"
echo "### ====================================================="

create_vm_apt_sources_list $MOUNT

echo "### ====================================================="
echo "### Cleaning up"
echo "### ====================================================="

binding_umount $MOUNT

sudo losetup -a > /tmp/${VMHOSTNAME}.loopdevlist
sudo mount | grep ^/dev/loop > /tmp/${VMHOSTNAME}.loopmount

# Umounting and Cleaning up loop devices
cleanup_loopdev

# rm -f $devlist

echo "Done."

# ---------------------------------------------------------------------	#
# end of file.								#
# ---------------------------------------------------------------------	#
